<?php
class Admin_Model_User {
	
	private $userTbl;
	
	function __construct(){
		$this->userTbl = new Admin_Model_DbTable_Users();	
	}
	
	public function listUser($where=null,$auth=null){
		$dbAdapter = Zend_Db_Table::getDefaultAdapter();
		$dbSelect = new Zend_Db_Select($dbAdapter);
		
		$dbSelect->from(array('u' => 'users'),array('*'))
				->joinLeft('sinhvien', 'sinhvien.username = u.username','idLop')
				->joinLeft('lop', 'lop.id = sinhvien.idLop',array('tenLop','khoa'));
				
		if($where !=null)$dbSelect->where($where);

		$dbSelect->order('ten ASC');	

		return $dbSelect;
	}
	
	/**
	 * 
	 * add 1 user vao bang users
	 * @param unknown_type $userName 
	 * @param unknown_type $password
	 * @param unknown_type $quyen
	 * @param unknown_type $hoDem
	 * @param unknown_type $ten
	 * @param unknown_type $email
	 * @param unknown_type $ngaySinh
	 */
	function addUser($userName, $password,$quyen, $hoDem,$ten, $email=null,$ngaySinh){
		$password = md5($password);
		$hoDem = ucwords($hoDem);
		$ten = ucwords($ten);
		
		$this->userTbl->insert(array(
			'username'		=>	$userName,
			'password'		=>	$password,
			'quyen'			=>	$quyen,
			'hoDem'			=>	$hoDem,
			'ten'			=>	$ten,
			'email'			=>	$email,
			'ngaysinh'		=>	$ngaySinh
		));
	}
	
	/**
	 * 
	 * Cap nhap lai thong tin user
	 * @param unknown_type $userName
	 * @param unknown_type $password
	 * @param unknown_type $quyen
	 * @param unknown_type $hoDem
	 * @param unknown_type $ten
	 * @param unknown_type $email
	 * @param unknown_type $ngaySinh
	 * @param unknown_type $id
	 */
	function updateUser($password,$quyen, $hoDem,$ten, $email=null,$ngaySinh, $userName){
		$password = md5($password);
		$hoDem = ucwords($hoDem);
		$ten = ucwords($ten);
		
		$this->userTbl->update(array(
									'password'		=>	$password,
									'quyen'			=>	$quyen,
									'hoDem'			=>	$hoDem,
									'ten'			=>	$ten,
									'email'			=>	$email,
									'ngaysinh'		=>	$ngaySinh
								), "username = '".$userName."'");
	}
	
	/**
	 * 
	 * Delete 1 user
	 * @param unknown_type $userName
	 */
	function deleteUser($userName){
		$this->userTbl->delete("username = '".$userName."'");
	}
	
	/**
	 * 
	 * Get tat cac cac ten lop
	 */
	function getAllLop(){
		$dbAdater = Zend_Db_Table::getDefaultAdapter();
		$dbSelect = new Zend_Db_Select($dbAdater);
		$dbSelect->from('lop','tenLop')
				->distinct(true);
				
		return $dbSelect->query();
	}
	
	/**
	 * 
	 * Lay thong tin cua 1 username
	 * @param unknown_type $username
	 */
	function fetchUser($username){
		 return $this->userTbl->fetchRow("username = '".$username."'");
	}
	
}